package com.hos.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/27 15:19
 * @description:
 * @modified By:
 * @version:
 */
public class MybatisPlusUtils {

    /**
     * @param mapper    持久DAO
     * @param condition
     * @param limit     随机条数
     * @return java.util.List<T>
     * @create by: 陈海彬
     * @description: 随机查询
     * @create time: 2023/12/27 15:19
     */
    public static <T> List<T> getAny(BaseMapper<T> mapper, T condition, Long limit) {
        LambdaQueryWrapper<T> wrapper = Wrappers.lambdaQuery(condition);
        Long total = mapper.selectCount(wrapper);
        if (limit == null || limit <= 0 || total == 0) {
            return Collections.emptyList();
        }
        List<T> list = Optional.of(limit)
                .filter(aLong -> aLong > total)
                .map(aLong -> mapper.selectList(wrapper))
                .orElseGet(() -> mapper.selectList(wrapper.last("LIMIT " + new SecureRandom().nextInt((int) (total - (limit - 1))) + "," + limit)));
        Collections.shuffle(list);
        return list;
    }
}